const { file } = require('jszip/lib/object')
const Mock = require('mockjs')

const orderList = []
const count = 100

for (let i = 0; i < count; i++) {
  orderList.push(Mock.mock({
    orderNo: 'ORD' + Mock.Random.date('yyyyMMdd') + Mock.Random.integer(1000, 9999),
    goodsId: Mock.Random.integer(1000, 1100),
    goodsName: Mock.Random.ctitle(3, 8),
    goodsImage: Mock.Random.image('100x100', Mock.Random.color(), Mock.Random.cword(2, 3)),
    machineId: Mock.Random.integer(2000, 2100),
    machineName: Mock.Random.ctitle(3, 8) + '贩卖机',
    price: Mock.Random.float(1, 50, 0, 2),
    quantity: Mock.Random.integer(1, 5),
    totalAmount: function () {
      return (this.price * this.quantity).toFixed(2)
    },
    paymentMethod: Mock.Random.pick(['alipay', 'wechat', 'cash']),
    status: Mock.Random.pick(['paid', 'unpaid', 'refunded']),
    createTime: Mock.Random.datetime('yyyy-MM-dd HH:mm:ss'),
    payTime: function () {
      return this.status === 'paid' || this.status === 'refunded' ?
        Mock.Random.datetime('yyyy-MM-dd HH:mm:ss') : null
    },
    refundTime: function () {
      return this.status === 'refunded' ?
        Mock.Random.datetime('yyyy-MM-dd HH:mm:ss') : null
    }
  }))
}

module.exports = [
  // 获取订单列表
  {
    url: '/api/order/list',
    type: 'get',
    response: config => {
      const { orderNo, goodsName, machineName, status, startTime, endTime, pageNum = 1, pageSize = 10 } = config.query

      let filteredList = [...orderList].filter(item => {
        if (orderNo && item.orderNo.indexOf(orderNo) < 0) return false
        if (goodsName && item.goodsName.indexOf(goodsName) < 0) return false
        if (machineName && item.machineName.indexOf(machineName) < 0) return false
        if (status && item.status !== status) return false

        if (startTime && endTime) {
          const createTime = new Date(item.createTime).getTime()
          const start = new Date(startTime).getTime()
          const end = new Date(endTime).getTime() + 86400000 // 加一天
          if (createTime < start || createTime > end) return false
        }

        return true
      })

      const pageList = filteredList.slice((pageNum - 1) * pageSize, pageNum * pageSize)

      return {
        code: 200,
        message: 'success',
        data: {
          list: pageList,
          total: filteredList.length
        }
      }
    }
  },

  // 订单退款
  {
    url: '/api/order/refund',
    type: 'post',
    response: config => {
      const { orderNo } = config.body
      const order = orderList.find(item => item.orderNo === orderNo)

      if (order) {
        order.status = 'refunded'
        order.refundTime = new Date().toISOString()
        return {
          code: 200,
          message: '退款成功'
        }
      } else {
        return {
          code: 404,
          message: '订单不存在'
        }
      }
    }
  },

  // 导出订单（CSV 格式）
  {
    url: '/api/order/export',
    type: 'get',
    response: config => {
      const { orderNo, goodsName, machineName, status, startTime, endTime } = config.query

      let filteredList = [...orderList].filter(item => {
        if (orderNo && item.orderNo.indexOf(orderNo) < 0) return false
        if (goodsName && item.goodsName.indexOf(goodsName) < 0) return false
        if (machineName && item.machineName.indexOf(machineName) < 0) return false
        if (status && item.status !== status) return false

        if (startTime && endTime) {
          const createTime = new Date(item.createTime).getTime()
          const start = new Date(startTime).getTime()
          const end = new Date(endTime).getTime() + 86400000 // 加一天
          if (createTime < start || createTime > end) return false
        }

        return true
      })

      // 模拟导出Excel文件
      const headers = ['订单号', '商品名称', '设备名称', '单价', '数量', '总金额', '支付方式', '订单状态', '下单时间']
      let csv = headers.join(',') + '\n'

      filteredList.forEach(item => {
        const row = [
          item.orderNo,
          item.goodsName,
          item.machineName,
          item.price,
          item.quantity,
          item.totalAmount,
          item.paymentMethod === 'alipay' ? '支付宝' :
            item.paymentMethod === 'wechat' ? '微信支付' : '现金',
          item.status === 'paid' ? '已完成' :
            item.status === 'unpaid' ? '未支付' : '已退款',
          item.createTime
        ]
        csv += row.join(',') + '\n'
      })
      return csv
    }
  }
]